<?php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: https://secure.s3.ierg4210.ie.cuhk.edu.hk");
session_start();

include_once("auth_process.php");
include_once("keys.php");

$authResult = validateSession();

if ($authResult['result'] == false) {
    //reject the operation

    echo json_encode(array('failed' => 'Not login '));
    exit();
} else {
    if (!isset($_POST['cart_token']) || $_POST['cart_token'] != $_SESSION['cart_token']) {
        echo json_encode(array('failed' => 'missing cart_token'));
        exit();
        //|| $_POST['cart_token']!= $_SESSION['cart_token']
    }

    if (isset($_POST['cart_items'])) {
        include_once("db_connection.php");
        $conn = getdb();
        $stmt = $conn->prepare("SELECT  pname, price  FROM products WHERE pid = :pid");

        $currency_code = "HKD";
        $charset = "utf-8";
        $merchant_email = getMerchantEmail();
        $uid = $_SESSION['ierg4210']["uid"];
        $salt = md5("cart" . time() . rand(0, 9999));
        $digest = "";
        $delimiter = "___";

        $digest = $currency_code . $delimiter . $merchant_email . $delimiter;
        $cart_items = json_decode($_POST['cart_items']);
        $cart_details = array();
        $cart_items = get_object_vars($cart_items);
        ksort($cart_items);
        $pnumber = 0;
        $total_price = 0;
        foreach ($cart_items as $pid => $quantity) {
            $stmt->bindParam(':pid', $pid);
            $stmt->execute();
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $current_product = $stmt->fetch();
            $price = $current_product['price'];
            $product_name = $current_product['pname'];
            $current_gross = $price * $quantity;

            $digest .= ($pid . $delimiter . $product_name . $delimiter . $quantity . $delimiter . number_format($current_gross, 2) . $delimiter);

            $detail = array("quantity" => $quantity, "price" => $price, "name" => $product_name);
            $cart_details[$pid] = $detail;

            $pnumber++;
            $total_price += $current_gross;
        }

        $digest .= number_format($total_price, 2);

        $digest_hash = hash_hmac("sha256", $digest, $salt);


        $stmt = $conn->prepare("INSERT INTO orders (oid,txn_id,uid,payment_status,currency_code,merchant_email,salt,digest,pnumber)
    VALUES (NULL,NULL, :uid, 0,:currency_code, :merchant_email,:salt,:digest,:pnumber)");
        $stmt->bindParam(':uid', $uid);
        $stmt->bindParam(':merchant_email', $merchant_email);
        $stmt->bindParam(':currency_code', $currency_code);
        $stmt->bindParam(':salt', $salt);
        $stmt->bindParam(':digest', $digest_hash);
        $stmt->bindParam(':pnumber', $pnumber);
        $stmt->execute();

        $oid = $conn->lastInsertId();

        echo json_encode(array(
                'success' => array(
                    'digest' => $digest_hash,
                    'order_id' => $oid,
                    'merchant_email' => $merchant_email,
                    'currency_code' => $currency_code,
                    'charset' => $charset,
                    'cart_details' => json_encode($cart_details)
                )
            )
        );
    } else {
        echo json_encode(array('failed' => 'missing cart_items parameter'));
    }
}
?>